from requests import post
import cv2
import numpy as np

import base64
from io import BytesIO
from PIL import Image
from control import get_event


def base64_to_cv(base64_string):
    # 将Base64字符串解码为二进制数据
    img_data = base64.b64decode(base64_string)

    # 将二进制数据转换为OpenCV图片格式
    np_img = np.frombuffer(img_data, np.uint8)

    # 使用imdecode函数读取图片，注意传入正确的解码参数
    opencv_image = cv2.imdecode(np_img, cv2.IMREAD_COLOR)
    return opencv_image


def image_to_binary(img):
    _, encoded_image = cv2.imencode('.jpg', img)
    binary_data = np.array(encoded_image).tobytes()
    return binary_data


cap = cv2.VideoCapture(0)
mem = [0,0,0,0,0]
while True:
    ret, frame = cap.read()
    maps = {
        "one": [0,0,0,2,0],
        "two": [0,0,2,2,0],
        "three": [0,2,2,2,0],
        "four": [2,2,2,2,0],
        "five": [2,2,2,2,2],
        "six": [2,0,0,0,2],
        "eight": [0,0,0,2,2],
        "zero": [0,0,0,0,0]
    }
    files = {'file': image_to_binary(frame)}
    response = post("http://192.168.121.1:8000/mask", files=files).json()
    if response["code"] == 0:
        # try:
        frame = base64_to_cv(response["img"])
        try:
            val = maps[response["label"][0]]
            if val == mem:
                frame = frame
            else:
                get_event(val)
                mem = val
        except:
            frame = frame


    else:
        frame = frame
    cv2.imshow("capture", frame)
    cv2.waitKey(1)
